package cn.blnp.net.flowable.boot.utils;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * <h3></h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/10 11:45
 */
public class SpELKeyGeneratorUtil {

    /**
     * 解析SpEL表达式生成key
     * @param spEL 表达式如 "'cache:' + #user.id"
     * @param methodParams 方法参数数组
     * @param paramNames 参数名数组
     */
    public static String generateKeyBySpEL(String spEL, Object[] methodParams, String[] paramNames) {
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext();

        // 将参数绑定到上下文
        for (int i = 0; i < methodParams.length; i++) {
            context.setVariable(paramNames[i], methodParams[i]);
        }

        Expression expression = parser.parseExpression(spEL);
        return expression.getValue(context, String.class);
    }
}
